/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.security.strategy;

import vip.dexian.admin.security.config.SecurityConfig;
import vip.dexian.common.Message;
import vip.dexian.common.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * session过期 策略
 *
 * @author 挺好的 2023年06月06日 17:10
 */
@Component
public class ExpiredSessionStrategy implements SessionInformationExpiredStrategy {

    @Override
    public void onExpiredSessionDetected (SessionInformationExpiredEvent event) throws IOException, ServletException {

        HttpServletRequest request = event.getRequest();
        HttpServletResponse response = event.getResponse();

        response.setStatus(HttpStatus.UNAUTHORIZED.value());


        // 如果不是ajax请求
        if (!WebUtils.isAjaxRequest(request)) {
            response.sendRedirect(SecurityConfig.LOGIN + "?isExpired=true");
            return;
        }

        WebUtils.responseMessage(response,
                Message.warn("登录超时或者账号在其他地方登录，如果密码遭到泄露，请立即修改密码！")
        );

    }
}
